import { reqShopCart, reqDeleteCartById, reqUpdateCheckedById } from '@/api'
const state = {
  cartList: []
}

//mutations 修改state的唯一手段
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }

}

//actions 可以书写的业务
const actions = {
  async getCartList({ commit }) {
    let result = await reqShopCart()
    if (result.code == 200) {
      commit('GETCARTLIST', result.data)
    }
  },
  async deleteCartListBySkuId({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      return '成功'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked)
    if (result.code == 200) {
      return '成功'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  deleteAllCheckedCart({ dispatch, getters }) {
    let promiseAll = []
    getters.cartList.cartInfoList.forEach(item => {
      let promise = item.isChecked == 1 ? dispatch('deleteCartListBySkuId', item.skuId) : ''
      promiseAll.push(promise)
    });
    return Promise.all(promiseAll)
  },
  updateAllCartIsChecked({ dispatch, state }, isChecked) {
    let promiseAll = []
    state.cartList[0].cartInfoList.forEach(item => {
      let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked })
      promiseAll.push(promise)
    })
    return Promise.all(promiseAll)
  }
}

//理解为计算属性用于简化仓库数 ，让组件读取数据更快
const getters = {
  cartList(state) {
    return state.cartList[0] || []
  }

}
export default {
  state,
  mutations,
  actions,
  getters
}